package me.shiqiang.im.action;


import com.tst.common.returnobj.BaseReturnObj;
import com.tst.common.returnobj.ReturnObjCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
@RequestMapping("im/file")
public class FileUploadAction {

    @Value("${upload.baseDir}")
    String baseDir;

    @PostMapping("/upload")
    public BaseReturnObj upload(@RequestParam("dir") String dir, @RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return new BaseReturnObj(ReturnObjCode.INVALID_PARAM, "不能上传空文件");
        }
        try {
            Path fileStorageLocation = Paths.get(baseDir).toAbsolutePath().normalize();
            if (!(Files.exists(fileStorageLocation) && Files.isDirectory(fileStorageLocation))) {
                Files.createDirectories(fileStorageLocation);
            }
            String fileName = multipartFile.getOriginalFilename();
            Path dest = fileStorageLocation.resolve(dir).resolve(fileName);
            // 创建所有必需的目录
            Files.createDirectories(dest.getParent());
            Files.copy(multipartFile.getInputStream(), dest, StandardCopyOption.REPLACE_EXISTING);
            return new BaseReturnObj(ReturnObjCode.SUCCESS, fileName);
        } catch (IOException e) {
            return new BaseReturnObj(ReturnObjCode.BUSINESS_EXCEPTION, "上传文件失败");
        }
    }

    @GetMapping(value = {"/download/{filename:.+}","/download/{dir:.*}/{filename:.+}"})
    public ResponseEntity<Resource> downloadFile( @PathVariable(required = false) String dir, @PathVariable String filename) {
        try {
//            filename = filename.replaceAll("..", "");
            Path fileStorageLocation = Paths.get(baseDir).toAbsolutePath().normalize();
            Path filePath = fileStorageLocation.resolve(dir).resolve(filename).normalize();
            if (!filePath.startsWith(fileStorageLocation)) {//防止路径遍历攻击
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            Resource resource = new UrlResource(filePath.toUri());

            if (!(resource.exists() || resource.isReadable())) {
                return ResponseEntity.notFound().build();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");
            String mimeType = Files.probeContentType(filePath);
            if (mimeType == null || mimeType.isEmpty()) {
                mimeType = "application/octet-stream"; // 或者其他适当的默认MIME类型
            }
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(Files.size(filePath))
                    .contentType(MediaType.parseMediaType(mimeType))
                    .body(resource);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

}
